package cn.alterzhang.www.test;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by zhangshuhan on 2019/1/30.
 */
public class ZKCurator {
    static String path = "/zk-boot";

    static CuratorFramework client = CuratorFrameworkFactory.newClient("198.181.39.68:2181", 5000, 3000, new ExponentialBackoffRetry(1000, 3));

    static CountDownLatch countDownLatch = new CountDownLatch(2);

    static ExecutorService executorService = Executors.newFixedThreadPool(2);

    public static void main(String[] args) throws Exception {
        client.start();
        System.out.println("main====" + Thread.currentThread().getName());
        client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).inBackground(new BackgroundCallback() {
            @Override
            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                System.out.println("ResultCode:" + event.getResultCode() + "=====type:" + event.getType());
                System.out.println("Thread.currentThread:java编程思想:name==" + Thread.currentThread().getName());
                countDownLatch.countDown();
            }
        }, executorService).forPath(path, "java编程思想".getBytes());


        client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).inBackground(new BackgroundCallback() {
            @Override
            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                System.out.println("ResultCode:" + event.getResultCode() + "=====type:" + event.getType());
                System.out.println("Thread.currentThread:java编程之美:name==" + Thread.currentThread().getName());
                countDownLatch.countDown();
            }
        }).forPath(path, "java编程之美".getBytes());
        countDownLatch.await();
        executorService.shutdown();
    }
}
